#include "widget.h"
#include "ui_widget.h"
#include <QMutex>
#include <QDebug>
#include "v4l2.h"

QMutex mutexSetR;

extern struct _control* in_parameters;
extern int parametercount;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    InitWidget();
}

Widget::~Widget()
{
    delete ui;
}
void Widget::InitWidget()
{
    setWindowTitle(tr("Wondfo Camera Demo"));
    err11 = err19 = 0;

    imageprocessthread = new MajorImageProcessingThread;

    ui->CameraNameComboBox->setMaxVisibleItems(10);
    ui->CameraNameComboBox->setStyleSheet("QComboBox{combobox-popup:0}");
    int deviceCount = GetDeviceCount();
    if(deviceCount > 0)
    {
        for(int i = 0; i < deviceCount; i++)
        {

               ui->CameraNameComboBox->addItem(QString::fromLatin1(GetCameraName(i)));
        }
    }
    for(int i = 0; i < ui->CameraNameComboBox->count(); i++)
    {
        if(QString::fromLatin1(GetCameraName(i)) == QString::fromLatin1(GetCameraName(i+1)))
        {
            QModelIndex index = ui->CameraNameComboBox->model()->index(i+1,0);
            QVariant v(0);
            ui->CameraNameComboBox->model()->setData(index, v, Qt::UserRole -1);
        }
        if(QString::fromLatin1(GetCameraName(i)).startsWith("rk",Qt::CaseSensitive))
        {
            QModelIndex index = ui->CameraNameComboBox->model()->index(i,0);
            QVariant v(0);
            ui->CameraNameComboBox->model()->setData(index, v, Qt::UserRole -1);
        }
        if(QString::fromLatin1(GetCameraName(i)).startsWith("Integrated",Qt::CaseSensitive))
            ui->CameraNameComboBox->setCurrentIndex(i-1);
    }

}

void Widget::on_SwitchBt_clicked()
{
    if(ui->SwitchBt->text() == "打开相机")
    {
        ui->SwitchBt->setText(tr("关闭相机"));
        ui->CameraNameComboBox->setEnabled(false);

        //打开相机
        qDebug()<<"ui->CameraNameComboBox->currentIndex()" << ui->CameraNameComboBox->currentIndex();
        StartRun(ui->CameraNameComboBox->currentIndex());
        imageprocessthread->init(ui->CameraNameComboBox->currentIndex());
        imageprocessthread->start();

        //获取所有分辨率
        ui->ResolutionComboBox->clear();
        int rescount = GetResolutinCount();
        int curW = GetCurResWidth();
        int curH = GetCurResHeight();
        for(int i = 0; i < rescount; i++)
        {
            QString rW = QString::number(GetResolutionWidth(i));
            QString rH = QString::number(GetResolutionHeight(i));
            QString res = rW + "X" + rH;
            ui->ResolutionComboBox->addItem(res);
            bool ok;
            if(curW == rW.toInt(&ok, 10) && curH == rH.toInt(&ok, 10))
                ui->ResolutionComboBox->setCurrentIndex(i);
        }
        enumerateControls();
        for(int i = 0; i < parametercount; i++)
        {
            if(in_parameters[i].ctrl.id == V4L2_SET_FOCUS_MODE)
            {
                int focusMode = v4l2GetControl(V4L2_SET_FOCUS_MODE);
                Qt::CheckState focusState = focusMode == 0 ? Qt::Unchecked : Qt::Checked;
                ui->FocusSlider->setDisabled(focusMode);
                ui->FocusCheckBox->setDisabled(focusState);
            }
            if(in_parameters[i].ctrl.id == V4L2_SET_FOCUS)
            {
                ui->FocusSlider->setMinimum(in_parameters[i].ctrl.minimum);
                ui->FocusSlider->setMaximum(in_parameters[i].ctrl.maximum);
                int focusValue = v4l2GetControl(V4L2_SET_FOCUS);
                ui->FocusSlider->setValue(focusValue);
            }
            if(in_parameters[i].ctrl.id == V4L2_SET_EXPOSURE_MODE)
            {
                int exposureMode = v4l2GetControl(V4L2_SET_EXPOSURE_MODE);
                qDebug("exposure mode = %d\n",exposureMode);
                Qt::CheckState ExposureState = exposureMode == 1 ? Qt::Unchecked : Qt::Checked;
                ui->ExposureCheckBox->setCheckState(ExposureState);
                if(exposureMode == 1)
                {
                   ui->ExposureSlider->setDisabled(false);
                }
                else
                {
                    ui->ExposureSlider->setDisabled(true);
                }

            }

            if(in_parameters[i].ctrl.id == V4L2_SET_EXPOSURE)
            {
                ui->ExposureSlider->setMinimum(in_parameters[i].ctrl.minimum);
                ui->ExposureSlider->setMaximum(in_parameters[i].ctrl.maximum);
                int exposureValue = v4l2GetControl(V4L2_SET_EXPOSURE);
                //ui->tE_exposure->setText(QString::number(exposureValue));
            }

            //saturation
            if(in_parameters[i].ctrl.id == V4L2_SET_SATURATION)
            {
                ui->SaturationSlider->setMinimum(in_parameters[i].ctrl.minimum);
                ui->SaturationSlider->setMaximum(in_parameters[i].ctrl.maximum);
                int saturationValue = v4l2GetControl(V4L2_SET_SATURATION);
                ui->SaturationSlider->setValue(saturationValue);
            }

            //contrast
            if(in_parameters[i].ctrl.id == V4L2_SET_CONTRAST)
            {
                ui->ContrastSlider->setMinimum(in_parameters[i].ctrl.minimum);
                ui->ContrastSlider->setMaximum(in_parameters[i].ctrl.maximum);
                int contrastValue = v4l2GetControl(V4L2_SET_CONTRAST);
                ui->ContrastSlider->setValue(contrastValue);
            }

            //brightness
            if(in_parameters[i].ctrl.id == V4L2_SET_BRIGHTNESS)
            {
                ui->BrightnessSlider->setMinimum(in_parameters[i].ctrl.minimum);
                ui->BrightnessSlider->setMaximum(in_parameters[i].ctrl.maximum);
                int brightnessValue = v4l2GetControl(V4L2_SET_BRIGHTNESS);
                ui->BrightnessSlider->setValue(brightnessValue);
            }

            //hue
            if(in_parameters[i].ctrl.id == V4L2_SET_HUE)
            {
                ui->HueSlider->setMinimum(in_parameters[i].ctrl.minimum);
                ui->HueSlider->setMaximum(in_parameters[i].ctrl.maximum);
                int hueValue = v4l2GetControl(V4L2_SET_HUE);
                ui->HueSlider->setValue(hueValue);
            }
        }
        connect(imageprocessthread, SIGNAL(SendMajorImageProcessing(QImage, int)),
                this, SLOT(ReceiveMajorImage(QImage, int)));
//        connect(ui->ResolutionComboBox, SIGNAL(currentIndexChanged(QString)),this, SLOT(SetResolution()));
        connect(ui->FocusCheckBox, SIGNAL(clicked()), this, SLOT(SetFocusMode()));
        connect(ui->FocusSlider, SIGNAL(valueChanged(int)), this, SLOT(SetFocusValue()));

        connect(ui->ExposureCheckBox, SIGNAL(clicked()), this, SLOT(SetExposureMode()));
        connect(ui->ExposureSlider, SIGNAL(valueChanged(int)), this, SLOT(SetExposureValue()));

        connect(ui->SaturationSlider, SIGNAL(valueChanged(int)), this, SLOT(SetSaturation()));
        connect(ui->ContrastSlider, SIGNAL(valueChanged(int)), this, SLOT(SetContrast()));
        connect(ui->BrightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(SetBrightness()));
        connect(ui->HueSlider, SIGNAL(valueChanged(int)), this, SLOT(SetHue()));
    }else{
        ui->SwitchBt->setText(tr("打开相机"));
        ui->CameraNameComboBox->setEnabled(true);

        imageprocessthread->stop();
        imageprocessthread->wait();
        StopRun();
    }
}
void Widget::ReceiveMajorImage(QImage image, int result)
{
    if(result == -1)
    {
        imageprocessthread->stop();
        imageprocessthread->wait();
        StopRun();
        QMessageBox::warning(this, tr("获取图像失败"), tr("获取设备图像超时！"),
                             QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    }else if (result > 0) {
        imageprocessthread->stop();
        imageprocessthread->wait();
        StopRun();
        QMessageBox::warning(this, tr("获取图像失败"), tr("打开设备失败！"),
                             QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    }
    if(!image.isNull())
    {
        ui->imageLabel->clear();
        switch (result) {
        case 0:
            err11 = err19 = 0;
            if(image.isNull())
                QMessageBox::warning(this,tr("获取图像失败"),tr("画面丢失"));
            else
                ui->imageLabel->setPixmap(QPixmap::fromImage(image.scaled(ui->imageLabel->size())));
            break;
        case 11:
            err11++;
            if(err11 == 10)
                QMessageBox::warning(this,tr("获取图像失败"),
                                     tr("设备已打开，但获取视频失败！\n请尝试切换USB端口后断开重试！"));
            break;
        case 19:
            err19++;
            if(err19 == 10)
                QMessageBox::warning(this,tr("获取图像失败"),tr("设备丢失！"));
            break;
//        default:
//            QMessageBox::warning(this,tr("获取图像失败"),tr("设备打开！"));
//            break;
        }
    }

}
int Widget::SetResolution()
{
    int Width, Height;
    QString res = ui->ResolutionComboBox->currentText();
    QStringList list = res.split("X");
    Width = list[0].toInt();
    Height = list[1].toInt();
    mutexSetR.lock();
    V4L2SetResolution(Width, Height);
    mutexSetR.unlock();
    return 0;
}
int Widget::SetFocusMode()
{
    int focusMode = ui->FocusCheckBox->isChecked() ? 1 : 0;
    v4l2SetControl(V4L2_SET_FOCUS_MODE, focusMode);
    ui->FocusCheckBox->setDisabled(focusMode);

    return 0;
}
int Widget::SetFocusValue()
{
    int focusMode = ui->FocusCheckBox->isChecked() ? 1 : 0;
    if(focusMode == 0)
    {
        int value = ui->FocusSlider->value();
        v4l2SetControl(V4L2_SET_FOCUS, value);
    }

    return 0;
}
int Widget::SetExposureMode()
{
    int exposureMode = ui->ExposureCheckBox->isChecked() ? 3 : 1;
    v4l2SetControl(V4L2_SET_EXPOSURE_MODE, exposureMode);
    if(exposureMode == 1)
    {
       ui->ExposureSlider->setDisabled(false);
    }
    else
    {
        ui->ExposureSlider->setDisabled(true);
    }

    return 0;
}
int Widget::SetExposureValue()
{
    int ret = 0;
    int exposureMode = ui->ExposureCheckBox->isChecked() ? 3 : 1;
    if(exposureMode == 1)
    {
        int value = ui->ExposureSlider->value();
        ret = v4l2SetControl(V4L2_SET_EXPOSURE, value);
    }

    return ret;
}
int Widget::SetSaturation()
{
    int ret = 0;
    int value = ui->SaturationSlider->value();
    ret = v4l2SetControl(V4L2_SET_SATURATION, value);
    return ret;
}

int Widget::SetContrast()
{
    int ret;
    int value = ui->ContrastSlider->value();
    ret = v4l2SetControl(V4L2_SET_CONTRAST, value);
    return ret = 0;
}

int Widget::SetBrightness()
{
    int ret = 0;
    int value = ui->BrightnessSlider->value();
    ret = v4l2SetControl(V4L2_SET_BRIGHTNESS, value);
    return ret;
}

int Widget::SetHue()
{
    int ret = 0;
    int value = ui->HueSlider->value();
    ret = v4l2SetControl(V4L2_SET_HUE, value);
    return ret;
}

void Widget::on_pushButton_clicked()
{}

void Widget::on_ExitBt_clicked()
{
    this->close();
}
